import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, SafetyOutlined } from '@ant-design/icons';
import api from '../utils/api';

export default function Register() {
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 发送验证码
  const handleSendCode = async () => {
    try {
      const phone = form.getFieldValue('phone');
      
      if (!phone) {
        message.error('请输入手机号');
        return;
      }
      
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        message.error('请输入正确的手机号');
        return;
      }

      setSendingCode(true);
      
      const res = await api.post('/sms/send-code', { phone });
      
      if (res.success) {
        message.success(res.message);
        
        // 开发环境显示验证码
        if (res.devCode) {
          message.info(`开发模式 - 验证码: ${res.devCode}`, 10);
        }
        
        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      }
    } catch (error) {
      message.error(error.response?.data?.message || '发送验证码失败');
    } finally {
      setSendingCode(false);
    }
  };

  // 注册
  const onFinish = async (values) => {
    setLoading(true);
    try {
      const res = await api.post('/auth/register', values);
      
      if (res.success) {
        message.success('注册成功！');
        setTimeout(() => {
          navigate('/login');
        }, 1500);
      }
    } catch (error) {
      message.error(error.response?.data?.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',
      padding: 20
    }}>
      <Card
        style={{
          width: 420,
          background: 'rgba(0, 0, 0, 0.7)',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(212, 175, 55, 0.3)',
          borderRadius: 16,
          boxShadow: '0 8px 32px rgba(212, 175, 55, 0.15)'
        }}
        bodyStyle={{ padding: 32 }}
      >
        <h2 style={{
          textAlign: 'center',
          marginBottom: 32,
          color: '#d4af37',
          fontSize: 26,
          fontWeight: 600
        }}>
          🍷 会员注册
        </h2>

        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          size="large"
          layout="vertical"
        >
          <Form.Item
            name="name"
            rules={[
              { required: true, message: '请输入姓名' },
              { min: 2, message: '姓名至少2个字符' }
            ]}
          >
            <Input
              prefix={<UserOutlined style={{ color: '#d4af37' }} />}
              placeholder="姓名"
              style={{
                background: 'rgba(255, 255, 255, 0.05)',
                border: '1px solid rgba(212, 175, 55, 0.2)',
                color: '#fff'
              }}
            />
          </Form.Item>

          <Form.Item
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input
              prefix={<PhoneOutlined style={{ color: '#d4af37' }} />}
              placeholder="手机号"
              maxLength={11}
              style={{
                background: 'rgba(255, 255, 255, 0.05)',
                border: '1px solid rgba(212, 175, 55, 0.2)',
                color: '#fff'
              }}
            />
          </Form.Item>

          <Form.Item
            name="smsCode"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码为6位数字' }
            ]}
          >
            <div style={{ display: 'flex', gap: 8 }}>
              <Input
                prefix={<SafetyOutlined style={{ color: '#d4af37' }} />}
                placeholder="验证码"
                maxLength={6}
                style={{
                  flex: 1,
                  background: 'rgba(255, 255, 255, 0.05)',
                  border: '1px solid rgba(212, 175, 55, 0.2)',
                  color: '#fff'
                }}
              />
              <Button
                onClick={handleSendCode}
                loading={sendingCode}
                disabled={countdown > 0}
                style={{
                  background: countdown > 0 ? 'rgba(212, 175, 55, 0.3)' : 'linear-gradient(135deg, #d4af37 0%, #f4e5a1 100%)',
                  border: 'none',
                  color: countdown > 0 ? '#999' : '#1a1a1a',
                  fontWeight: 600,
                  minWidth: 110
                }}
              >
                {countdown > 0 ? `${countdown}秒` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码至少6位' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#d4af37' }} />}
              placeholder="密码（至少6位）"
              style={{
                background: 'rgba(255, 255, 255, 0.05)',
                border: '1px solid rgba(212, 175, 55, 0.2)',
                color: '#fff'
              }}
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: '#d4af37' }} />}
              placeholder="确认密码"
              style={{
                background: 'rgba(255, 255, 255, 0.05)',
                border: '1px solid rgba(212, 175, 55, 0.2)',
                color: '#fff'
              }}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{
                background: 'linear-gradient(135deg, #d4af37 0%, #f4e5a1 100%)',
                border: 'none',
                height: 48,
                fontSize: 16,
                fontWeight: 600,
                color: '#1a1a1a',
                boxShadow: '0 4px 12px rgba(212, 175, 55, 0.3)'
              }}
            >
              注册
            </Button>
          </Form.Item>

          <div style={{
            textAlign: 'center',
            color: 'rgba(255, 255, 255, 0.5)',
            fontSize: 14
          }}>
            已有账号？
            <a
              onClick={() => navigate('/login')}
              style={{
                color: '#d4af37',
                marginLeft: 8,
                cursor: 'pointer'
              }}
            >
              立即登录
            </a>
          </div>
        </Form>
      </Card>
    </div>
  );
}
